<template>
  <div>
    <el-card class="box-card mb15 header-form">
      <el-row>
        <el-col :span="22">
          <el-row :gutter="20">
            <el-col :xs="8" :sm="8" :md="8" :lg="5">
              <span style="margin-right: 12px">ip地址</span>
              <el-input
                size="mini"
                style="width: 75%"
                placeholder="ip地址"
                v-model="listQuery.ipAddr"
                clearable
              >
              </el-input
            ></el-col>
            <el-col :xs="8" :sm="8" :md="8" :lg="5">
              <span style="margin-right: 12px">名称</span>
              <el-input
                size="mini"
                style="width: 75%"
                placeholder="请输入名称"
                v-model="listQuery.name"
                clearable
              >
              </el-input
            ></el-col>

            <el-col :xs="12" :sm="8" :md="8" :lg="7">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="search()"
                style="float: left; width: 100px"
                class="jurisdiction"
                >搜索</el-button
              >
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="2" style="text-align: right">
          <el-button
            type="primary"
            size="mini"
            @click="addIpAddress()"
            style="float: left; width: 100px"
            class="jurisdiction"
            >新增</el-button
          >
        </el-col>
      </el-row>
    </el-card>
    <el-card class="box-card mb15">
      <el-menu
        class="el-menu-demo"
        mode="horizontal"
        :default-active="listQuery.type"
        background-color="#ffffff"
        @select="handleClick"
      >
        <el-menu-item v-for="(v, i) in typeData" :key="i" :index="v.value">{{
          v.label
        }}</el-menu-item>
      </el-menu>
      <el-table :data="blacklistTableData" style="width: 100%" stripe>
        <el-table-column fixed prop="ipAddr" label="IP地址"> </el-table-column>
        <el-table-column prop="name" label="名称"> </el-table-column>
        <!-- <el-table-column prop="del" label="是否可用" width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.del | blackDelStyleFilter">
              {{ scope.row.del | blackDelNameFilter }}</el-tag
            >
          </template>
        </el-table-column> -->
        <el-table-column prop="createName" label="创建人" width="120">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
        </el-table-column>
        <el-table-column prop="updateTime" label="修改时间" width="160">
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template slot-scope="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                size="mini"
                @click="showEditDialog(row)"
                class="jurisdiction"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="showDeleDialog(row)"
                class="jurisdiction"
                >删除</el-button
              >
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        style="margin-top: 20px"
        v-show="parseInt(pageObj.count) > 0"
        :total="parseInt(pageObj.count)"
        @change="getList"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
      />
    </el-card>

    <el-dialog
      :title="dialogTitle"
      class="dialog-wrap"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="800px"
    >
      <div class="dialog-cont" v-loading="dialogLoading">
        <div>
          <el-form
            :model="ruleForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="分类" prop="type" style="margin-bottom: 24px">
              <el-select
                v-model="ruleForm.type"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="黑名单" value="1"> </el-option>
                <el-option label="白名单" value="2"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="名称" prop="name" style="margin-bottom: 24px">
              <el-input
                type="input"
                style="width: 100%"
                v-model="ruleForm.name"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="IP地址" prop="ipAddr" class="ipAddr">
              <template>
                <span class=""></span>
                <ul class="ipAdress" style="width: 100%">
                  <li v-for="(item, index) in ipAddressItem" :key="index">
                    <input
                      ref="ipInput"
                      v-model="item.value"
                      type="text"
                      class="ipInputClass"
                      @input="checkIpVal(item)"
                      @keyup="turnIpPosition(item, index, $event)"
                    />
                    <div></div>
                  </li>
                </ul>
                <div class="el-form-item__error" v-show="ipShow">
                  请输入正确的IP地址
                </div>
              </template>
            </el-form-item>
            <!-- <el-form-item label="是否可用" prop="del" class="le-radio">
              <el-radio-group v-model="ruleForm.del">
                <el-radio label="1">可用</el-radio>
                <el-radio label="2">不可用</el-radio>
              </el-radio-group>
            </el-form-item> -->
          </el-form>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <span class="dialog-footer">
          <el-button @click="resetForm('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确 定</el-button
          >
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  tbSysBlackQuery,
  tbSysBlackAdd,
  tbSysBlackUpdate,
  tbSysBlackDelete,
} from '@/api/admin/system/black-manage'
export default {
  created() {
    this.getList()
  },
  data() {
    return {
      temp: {},
      listQuery: {
        page: 1,
        limit: 10,
        name: '',
        ipAddr: '',
        type: '1',
        // del: "",
      },
      typeData: [
        { label: '黑名单', value: '1' },
        { label: '白名单', value: '2' },
      ],
      blacklistTableData: [],
      dialogVisible: false,
      dialogFormVisible: false,
      loading: true,
      dialogLoading: false,
      pageObj: {},
      options: [
        {
          value: '1',
          label: '可用',
        },
        {
          value: '2',
          label: '不可用',
        },
      ],
      dialogTitle: '黑名单管理-新增',
      addType: 1,
      ruleForm: {
        name: '',
        del: '',
        id: '',
        type: '1',
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            min: 2,
            max: 12,
            message: '长度在 2 到 12 个字符',
            trigger: 'blur',
          },
        ],

        // del: [{ required: true, message: "请选择是否可用", trigger: "change" }],
      },
      ipAddressItem: [
        {
          value: '',
        },
        {
          value: '',
        },
        {
          value: '',
        },
        {
          value: '',
        },
      ],
      ipShow: false,
    }
  },
  components: {},
  watch: {
    ipAddressItem: {
      // 双向数据绑定的value
      handler: function (newVal, oldVal) {
        let str = ''
        for (const i in this.ipAddressItem) {
          str += this.formatter(this.ipAddressItem[i].value)
        }
        if (str === '000000000000') {
          str = ''
        }
      },
      deep: true,
    },
  },
  methods: {
    search() {
      this.listQuery.page = 1
      this.getList()
    },
    //切换页签
    handleClick(tab) {
      this.listQuery.type = tab
      this.getList()
    },
    //获取列表
    getList() {
      tbSysBlackQuery(this.listQuery).then((res) => {
        this.blacklistTableData = res.data.data
        this.pageObj = res.data
      })
    },
    //删除
    showDeleDialog(row) {
      this.temp = { ...row }
      this.$confirm('确认删除？删除之后不再恢复！', '提示', {
        type: 'warning',
      })
        .then((_) => {
          var data = { id: this.temp.id, name: this.temp.name }
          const loading = this.openLoading()
          tbSysBlackDelete(this.temp.id).then((res) => {
            if (res.data.code == 0) {
              this.$message.success(res.data.msg)

              this.getList()
            } else {
              this.$message.error(res.data.msg)
            }
            loading.close()
          })
        })
        .catch((_) => {})
    },
    handleDelete() {
      let { id, name } = this.temp
      const loading = this.openLoading()
      tbSysBlackDelete({ id, name }).then((res) => {
        this.$notify.error({
          title: '删除',
          message: '删除成功',
          duration: 1000,
        })
        loading.close()
        this.dialogVisible = false
        this.getList()
      })
    },
    //编辑
    showEditDialog(row) {
      this.temp = { ...row }
      this.dialogVisible = true
      this.dialogTitle = '编辑'
      this.dialogVisible = true
      this.ipShow = false
      this.ruleForm.name = this.temp.name
      this.ruleForm.del = this.temp.del
      this.ruleForm.id = this.temp.id
      var arr = this.temp.ipAddr.split('.')
      this.addType = 2

      this.ipAddressItem.forEach((e, eindex) => {
        arr.forEach((a, aindex) => {
          if (eindex == aindex) {
            e.value = a
          }
        })
      })
    },
    handleUpdate() {
      const loading = this.openLoading()
      tbSysBlackUpdate(this.temp).then((res) => {
        this.$message.success(res.data.msg)
        this.dialogFormVisible = false
        this.getList()
        loading.close()
      })
    },
    //新增
    addIpAddress() {
      this.dialogVisible = true
      this.ipShow = false
      this.ruleForm.name = ''
      this.ruleForm.del = ''
      this.ruleForm.type = this.listQuery.type
      this.dialogTitle = '新增'
      this.addType = 1
      this.ipAddressItem.forEach((e) => {
        e.value = ''
      })
    },
    // 取消
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.dialogVisible = false
    },

    //保存
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var type = true
          var arr = []
          if (this.ipAddressItem[0].value === '') {
            type = false
          }
          this.ipAddressItem.forEach((e) => {
            arr.push(e.value)
          })

          if (type) {
            this.ipShow = false
            var data = {
              name: this.ruleForm.name,
              //del: this.ruleForm.del,
              ipAddr: arr.join('.'),
              type: this.ruleForm.type,
            }

            if (this.addType == 2) {
              const loading = this.openLoading()
              this.dialogLoading = true
              ;(data.id = this.ruleForm.id),
                tbSysBlackUpdate(data).then((res) => {
                  this.dialogLoading = false
                  if (res.data.code == 0) {
                    this.$message.success('保存成功')
                    this.dialogVisible = false

                    this.getList()
                  } else {
                    this.$message.error(res.data.msg)
                  }
                  loading.close()
                })
            } else {
              this.dialogLoading = true
              const loading = this.openLoading()
              tbSysBlackAdd(data).then((res) => {
                this.dialogLoading = false
                if (res.data.code == 0) {
                  this.$message.success('保存成功')
                  this.dialogVisible = false

                  this.getList()
                } else {
                  this.$message.error(res.data.msg)
                }
                loading.close()
              })
            }
          } else {
            this.ipShow = true
          }
        } else {
          this.ipShow = false
          this.ipAddressItem.forEach((e) => {
            if (e.value == '') {
              this.ipShow = true
            }
          })
          return false
        }
      })
    },
    formatter(val) {
      let value = val.toString()
      if (value.length === 2) {
        value = '0' + value
      } else if (value.length === 1) {
        value = '00' + value
      } else if (value.length === 0) {
        value = '000'
      }
      return value
    },
    // 检查ip输入为0-255
    checkIpVal(item) {
      //确保每个值都处于0-255
      let val = item.value
      // 处理非数字
      val = val.toString().replace(/[^0-9]/g, '')
      val = parseInt(val, 10)
      if (isNaN(val)) {
        val = ''
      } else {
        val = val < 0 ? 0 : val
        val = val > 255 ? 255 : val
      }
      item.value = val
    },
    // 光标位置判断
    turnIpPosition(item, index, event) {
      let self = this
      let e = event || window.event
      if (e.keyCode === 37) {
        // 左箭头向左跳转，左一不做任何措施
        if (index !== 0 && e.currentTarget.selectionStart === 0) {
          self.$refs.ipInput[index - 1].focus()
        }
      } else if (e.keyCode == 39) {
        // 右箭头向右跳转，右一不做任何措施
        if (
          index !== 3 &&
          e.currentTarget.selectionStart === item.value.toString().length
        ) {
          self.$refs.ipInput[index + 1].focus()
        }
      } else if (e.keyCode === 8) {
        // 删除键把当前数据删除完毕后会跳转到前一个input，左一不做任何处理
        if (index !== 0 && item.value === '') {
          self.$refs.ipInput[index - 1].focus()
        }
      } else if (e.keyCode === 13 || e.keyCode === 32 || e.keyCode === 190) {
        // 回车键、空格键、冒号均向右跳转，右一不做任何措施
        if (index !== 3) {
          self.$refs.ipInput[index + 1].focus()
        }
      } else if (item.value.toString().length === 3) {
        // 满3位，光标自动向下一个文本框
        if (index !== 3) {
          self.$refs.ipInput[index + 1].focus()
        }
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.header-form {
  padding: 20px 10px 20px 50px !important;
}
.header-form /deep/ .el-card__body {
  background: #f7f8f9;
}
.dialog-wrap {
  .ipAdress {
    display: flex;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    width: 215px;
    height: 36px;
    padding-inline-start: 0px;
    margin-block-start: 0;
    margin-block-end: 0;
  }
  .ipAdress li {
    position: relative;
    height: 36px;
    margin: 0;
    list-style-type: none;
  }
  .ipInputClass {
    border: none;
    width: 49px;
    height: 23px;
    text-align: center;
    background: transparent;
  }
  .ipAdress li div {
    position: absolute;
    bottom: 8px;
    right: 0;
    border-radius: 50%;
    background: #505050;
    width: 2px;
    height: 2px;
  }
  /*只需要3个div*/
  .ipAdress li:last-child div {
    display: none;
  }
  /*取消掉默认的input focus状态*/
  .ipAdress input:focus {
    outline: none;
  }
}

.el-form-item.le-radio.el-form-item--feedback.is-required
  .el-form-item__content {
  text-align: left;
}
.dialog-wrap .el-form-item__label:before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
.left-menu {
  display: block;
}
</style>